<template>
    <div>
        <div class="search-term">
            <el-form :inline="true" :model="searchInfo" class="demo-form-inline">
                <el-form-item>
                    <el-input
                            placeholder="请输入商品名称"
                            v-model="searchInfo.goodsName"
                            clearable
                            size="small"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="status">
                    <el-select
                            v-model="searchInfo.goodsType"
                            placeholder="请选择分类"
                            clearable
                            size="small"
                    >
                        <el-option
                                v-for="item in typeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="onSubmit" type="primary" size="mini"
                    >搜 索
                    </el-button
                    >
                    <el-button @click="addGoods" type="primary" size="mini"
                    >新 增
                    </el-button
                    >
                </el-form-item>
            </el-form>
        </div>
        <el-table :data="tableData" style="width: 100%;margin-bottom: 10px;" border>
            <el-table-column prop="username" label="商品图片" align="center">
            </el-table-column>
            <el-table-column prop="education" label="商品名称" align="center">
            </el-table-column>
            <el-table-column prop="areaName" label="分类" align="center">
            </el-table-column>
            <el-table-column prop="mobile" label="价格" align="center">
            </el-table-column>
            <el-table-column prop="mobile" label="销量" align="center">
            </el-table-column>
            <el-table-column prop="mobile" label="库存" align="center">
            </el-table-column>
            <el-table-column prop="mobile" label="状态" align="center">
            </el-table-column>
            <el-table-column fixed="right" label="操作" align="center" width="300px">
                <template slot-scope="scope">
                    <el-button
                            @click="viewSchool(scope.row)"
                            size="mini"
                            type="info"
                            icon="el-icon-view"

                    >查看
                    </el-button
                    >
                    <el-button
                            @click="openClassDetail(scope.row)"
                            size="mini"
                            type="primary"
                            icon="el-icon-edit"
                    >编辑
                    </el-button>
                    <el-button
                            @click="openClassDetail(scope.row)"
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                :current-page="currPage"
                :page-size="pageSize"
                :page-sizes="[10, 20, 30, 50, 100]"
                :style="{ float: 'right', padding: '20px' }"
                :total="totalCount"
                @current-change="handlepageChange"
                @size-change="handleSizeChange"
                layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
        <!--商品弹出框-->
        <el-dialog
                :before-close="closeDialog"
                :title="dialogTitle"
                :visible.sync="dialogFormVisible"
                class="dialogs"
        >
            <el-form
                    :model="form"
                    :inline="true"
                    :rules="rules"
                    label-width="80px"
                    ref="areaForm"
            >
                <el-divider content-position="left">基本信息</el-divider>
                <el-form-item label="商品封面" prop="goodsCoverImg" class="pics">
                    <el-upload
                            class="avatar-uploader"
                            :action="`${path}/api-system/file/upload/goods`"
                            list-type="picture-card"
                            :show-file-list="false"
                            :before-upload="checkFile"
                            :headers="{ Authorization: token }"
                            :on-error="uploadError"
                            :on-success="uploadSuccess"
                    >
                        <div class="header-background">
                            <img v-if="isShowImg" :src="form.goodsCoverImg" class="avatar" width="100%" height="100%"/>
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品名称" prop="username">
                    <el-input
                            autocomplete="off"
                            v-model="form.username"
                            size="small"
                            placeholder="请输入商品名称"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="商品分类" prop="roleId">
                    <el-select
                            v-model="form.roleId"
                            placeholder="请选择角色"
                            size="small"
                            clearable
                    >
                        <el-option
                                v-for="item in typeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="单位" prop="username">
                    <el-input
                            autocomplete="off"
                            v-model="form.username"
                            size="small"
                            placeholder="请输入单位"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-divider content-position="left">规则信息</el-divider>
                <el-form-item label="商品编号" prop="username">
                    <el-input
                            autocomplete="off"
                            v-model="form.username"
                            size="small"
                            placeholder="请输入商品编号"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="成本价" prop="username">
                    <el-input
                            autocomplete="off"
                            v-model="form.username"
                            size="small"
                            placeholder="请输入成本价"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="售价" prop="username">
                    <el-input
                            autocomplete="off"
                            v-model="form.username"
                            size="small"
                            placeholder="请输入售价"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-form-item label="库存" prop="username">
                    <el-input
                            autocomplete="off"
                            v-model="form.username"
                            size="small"
                            placeholder="请输入库存"
                            clearable
                    ></el-input>
                </el-form-item>
                <el-divider content-position="left">商品详情</el-divider>
                <quill-editor
                        style=" height: 400px;"
                        :options="editorOption"
                        @blur="onEditorBlur($event)"
                        @change="onEditorChange($event)"
                        @focus="onEditorFocus($event)"
                        ref="myQuillEditor"
                        v-model="form.content"

                ></quill-editor>

                <el-upload class="avatar-uploader quill-img"
                           :action="`${path}/api-system/file/upload/goods`"
                           :show-file-list="false"
                           :headers="{ Authorization: token }"
                           :on-success="quillImgSuccess"
                           :before-upload="checkFile">
                </el-upload>

            </el-form>
            <div class="dialog-footer" slot="footer">
                <el-button @click="closeDialog" size="mini">取 消</el-button>
                <el-button @click="enterDialog" type="primary" size="mini"
                >确 定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    // 获取列表内容封装在mixins内部  getTableData方法 初始化已封装完成 条件搜索时候 请把条件安好后台定制的结构体字段 放到 this.searchInfo 中即可实现条件搜索
    import {mapGetters} from "vuex";
    import {goodsList} from "@/api/goods";
    import infoList from "@/components/mixins/infoList";

    export default {
        name: "goods",
        mixins: [infoList],
        data() {
            return {
                path: process.env.VUE_APP_BASE_API,
                typeOptions: [{
                    value: 0,
                    label: "教材",
                }, {
                    value: 1,
                    label: "教具",
                }],
                isShowImg: false,
                dialogTitle: "",
                dialogFormVisible: false,
                listApi: goodsList,
                searchInfo: {},
                btns: [],
                form: {},
                rules: {},
                editorOption: {
                    placeholder: '请输入商品详情...',
                    theme: 'snow', // 主题
                    modules: {
                        toolbar: {
                            container: [
                                ['bold', 'italic', 'underline', 'strike'],    // 加粗，斜体，下划线，删除线
                                [{indent: '-1'}, {indent: '+1'}],     // 缩进
                                [{header: [1, 2, 3, 4, 5, 6, false]}],     // 几级标题
                                [{color: []}, {background: []}],     // 字体颜色，字体背景颜色
                                [{align: []}],    // 对齐方式
                                ['image'],    // 上传图片
                                ['clean'],    // 清除字体样式
                            ],
                            handlers: {
                                image: function () {
                                    document.querySelector('.quill-img input').click()
                                }
                            }
                        }
                    },
                    // 图片上传的设置
                    uploadConfig: {
                        action: '`${path}/api-system/file/upload/goods`',  // 必填参数 图片上传地址
                        // 必选参数  res是一个函数，函数接收的response为上传成功时服务器返回的数据
                        // 你必须把返回的数据中所包含的图片地址 return 回去
                        res: (respnse) => {
                            return respnse.info
                        },
                        methods: 'POST',  // 可选参数 图片上传方式  默认为post
                        token: sessionStorage.token,  // 可选参数 如果需要token验证，假设你的token有存放在sessionStorage
                        name: 'img',  // 可选参数 文件的参数名 默认为img
                        size: 500,  // 可选参数   图片限制大小，单位为Kb, 1M = 1024Kb
                        accept: 'image/png, image/gif, image/jpeg, image/bmp, image/x-icon',  // 可选参数 可上传的图片格式
                        // start: function (){}
                        start: () => {
                        },  // 可选参数 接收一个函数 开始上传数据时会触发
                        end: () => {
                        },  // 可选参数 接收一个函数 上传数据完成（成功或者失败）时会触发
                        success: () => {
                        },  // 可选参数 接收一个函数 上传数据成功时会触发
                        error: () => {
                        }  // 可选参数 接收一个函数 上传数据中断时会触发
                    },
                    // 以下所有设置都和vue-quill-editor本身所对应
                    toolOptions: [],  // 可选参数  选择工具栏的需要哪些功能  默认是全部
                    handlers: {}  // 可选参数 重定义的事件，比如link等事件
                }
            };
        },
        computed: {
            editor() {
                return this.$refs.myQuillEditor.quill
            },
            ...mapGetters("user", ["userInfo", "token"]),
        },
        methods: {
            //条件搜索前端看此方法
            onSubmit() {
                this.page = 1;
                this.pageSize = 10;
                this.getTableData();
            },
            addGoods() {
                this.dialogFormVisible = true;
                this.dialogTitle = "新增商品";
            },
            closeDialog() {
                this.dialogFormVisible = false;
                this.dialogTitle = "";
            },
            enterDialog() {
                console.log(this.form)
            },
            onEditorBlur(e) {

            }, // 失去焦点事件
            onEditorFocus(e) {

            }, // 获得焦点事件
            onEditorChange(e) {

            },
            // 富文本编辑框图片上传
            quillImgSuccess(res, file) {
                // 获取富文本组件实例
                let quill = this.$refs.myQuillEditor.quill;
                // 如果上传成功
                if (res.statusCode === 0) {
                    // 获取光标所在位置
                    let length = quill.getSelection().index;
                    // 插入图片  res.data为服务器返回的图片地址
                    quill.insertEmbed(length, 'image', res.data);// 这里的url是图片的访问路径不是真实物理路径
                    // 调整光标到最后
                    quill.setSelection(length + 1)
                } else {
                    this.$message.error('图片插入失败')
                }
            },
            // 内容改变事件
            checkFile(file) {
                this.isShowImg = false;
                this.form.goodsCoverImg = '';
                this.fullscreenLoading = true;
                const isJPG = file.type === "image/jpeg";
                const isPng = file.type === "image/png";
                const isLt2M = file.size / 1024 / 1024 < 10;
                if (!isJPG && !isPng) {
                    this.$message.error("上传头像图片只能是 JPG或png 格式!");
                    this.fullscreenLoading = false;
                }
                if (!isLt2M) {
                    this.$message.error("上传头像图片大小不能超过 2MB!");
                    this.fullscreenLoading = false;
                }
                return (isPng || isJPG) && isLt2M;
            },
            uploadSuccess(res) {
                this.fullscreenLoading = false;
                if (res.statusCode === 0) {
                    this.$message({
                        type: "success",
                        message: "上传成功",
                    });
                    this.saveFlag = true;
                    this.isShowImg = true;
                    this.form.goodsCoverImg = res.data;
                } else {
                    this.$message({
                        type: "warning",
                        message: res.msg,
                    });
                }
            },
            uploadError() {
                this.$message({
                    type: "error",
                    message: "上传失败",
                });
                this.saveFlag = true;
                this.fullscreenLoading = false;
            },
        },
        async created() {
            this.searchInfo.currentAreaId = this.userInfo.areaId;
            this.getTableData();
        },
    };
</script>
<style scoped lang="scss">
    .info {
        color: #409EFF;
    }

    .warning {
        color: #E6A23C;
    }

    .success {
        color: #67c23a;
    }

    .danger {
        color: #f56c6c;
    }

    .green {
        color: #67c23a;
    }

    .red {
        color: #f56c6c;
    }

    .button-box {
        // padding: 10px 20px;
        .el-button {
            float: right;
        }
    }

    .el-tag--mini {
        margin-left: 5px;
    }

    .dialogs {
        ::v-deep .el-input-group--append .el-input__inner {
            width: 170px !important;
        }

        ::v-deep .el-dialog__body {
            padding: 15px 20px 10px 20px;
        }

        ::v-deep .el-input__inner {
            width: 225px;
        }

        ::v-deep .el-textarea__inner {
            width: 225px;
        }

        .dialog-footer {
            text-align: center;
            padding: 25px 0px 0px;
        }

        ::v-deep .el-input-number .el-input__inner {
            width: 130px;
        }

        ::v-deep .el-form .el-form-item {
            width: 49%;
            margin: 0;
            font-weight: 700
        }


        ::v-deep .el-form .pics {
            width: 100%;
            margin-bottom: 22px;
        }

        ::v-deep .el-form .el-divider .el-divider__text {
            font-weight: bold;
            color: #409EFF;
        }

        ::v-deep .el-form .el-form-item .el-form-item__content {
            width: calc(100% - 112px)
        }

        ::v-deep .el-form .el-form-item .el-form-item__content .el-textarea__inner {
            width: 100%;
        }

        ::v-deep strong {
            font-weight: bolder !important;
        }

        ::v-deep em {
            font-style: italic !important;
        }

        ::v-deep strong > em {
            font-weight: bolder !important;
            font-style: italic !important;
        }

    }


    .warning {
        color: #dc143c;
    }
</style>
